from flask import Blueprint, request, session, jsonify

import models
from common import Result
from exts import db, model_to_str_dict, predict_tea_price
from models import User

bp = Blueprint("admin_api", __name__, url_prefix="/api/admin")


@bp.route("/login", methods=["POST"])
def login():
    username = request.values.get("username")
    password = request.values.get("password")
    # print(username, password)

    user = db.session.query(User).filter(User.username == username).first()
    if user is None:
        return Result.error(
            msg="没有此用户"
        )
    else:
        if user.password == password:
            session["user"] = {
                "username": username,
                "password": password
            }
            return Result.success(
                msg="登录成功"
            )
        else:
            return Result.error(
                msg="密码错误"
            )


@bp.route("/register", methods=["POST"])
def register():
    username = request.values.get("username")
    password = request.values.get("password")

    user = db.session.query(User).filter(User.username == username).first()
    if user is None:
        user = User(
            username=username,
            password=password
        )
        db.session.add(user)
        db.session.commit()
        return Result.success(
            msg="注册成功"
        )
    else:
        return Result.error(
            msg="用户已存在"
        )


@bp.route("/login_out", methods=["GET"])
def login_out():
    del session["user"]
    return {"success": True}


@bp.route("/price_prediction", methods=["GET"])
def price_prediction():
    tea_name = request.values.get("tea_name")

    # 读取数据库数据
    models_all = db.session.query(models.Commodity).all()
    tea_data = []
    tea_data_set = set()
    for model in models_all:
        if model.name and model.price:
            tea_data.append([model.name, model.price])
            tea_data_set.add(model.name)

    if tea_name not in tea_data_set:
        return jsonify({
            "name": tea_name,
            "prince": 0,
            "msg": "无相关数据，无法预测"
        })
    # 进行预测
    predicted_price = predict_tea_price(tea_data, tea_name)
    return jsonify({
        "name": tea_name,
        "price": '{:.2f}'.format(predicted_price),
        "msg": "预测成功"
    })


@bp.route("/price_sales", methods=["GET"])
def price_sales():

    tea_name = request.values.get("tea_name")

    # 读取数据库数据
    models_all = db.session.query(models.Commodity).all()
    tea_data = []
    tea_data_set = set()
    for model in models_all:
        if model.name and model.price:
            tea_data.append([model.name, model.sales_volume])
            tea_data_set.add(model.name)

    if tea_name not in tea_data_set:
        return jsonify({
            "name": tea_name,
            "prince": 0,
            "msg": "无相关数据，无法预测"
        })
    # 进行预测
    sales_volume = predict_tea_price(tea_data, tea_name)
    return jsonify({
        "name": tea_name,
        "sales_volume": int(sales_volume),
        "msg": "预测成功"
    })


@bp.route("/all_tea_data", methods=["GET"])
def all_tea_data():
    return jsonify(list(map(
        model_to_str_dict,
        db.session.query(models.Commodity).all()
    )))
